package com.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class TimeTask {

    @Value("${server.port}")
    private  String port;

    @Autowired
    private RedissonClient redisClient;

    @Scheduled(cron = "0/10 * * * * ?")
    public void happyBirthday() throws InterruptedException {
        //仅仅实例锁对象
        RLock  rLock = redisClient.getLock("happy");
        //如果我没有锁的情况，最多等3秒，3秒没到，就f=false,执行下面代码
        //如果3秒内获取锁，则f=true,也执行下面代码
        //如果我获取锁，最多在里面等5秒
        boolean f = rLock.tryLock(3000,5000, TimeUnit.MILLISECONDS);
        if (f) {
            System.out.println(port + "发来生日快乐~" + new Date().toLocaleString());
            Thread.sleep(8000);
        }
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void happyBirthday2() throws InterruptedException {
        System.out.println(port + "发来生日快乐~" + new Date().toLocaleString());
    }
}













